<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="X-UA-Compatible" content="IE=EDGE" charset=UTF-8/>
		<link rel="stylesheet" type="text/css" href="resources/styles/GeneralStyle.css"/>
		<title>BCF - Method Definition Page</title>
		<script id="sap-ui-bootstrap"
	  		data-sap-ui-theme="sap_ux"
      		type="text/javascript"
       		data-sap-ui-libs="sap.ui.commons"
      		src="resources/sap-ui-core.js">
    	</script >
    	<script src="resources/JavaScript/common.js"></script>
		<script src="resources/JavaScript/utils.js"></script>
		<script src="resources/JavaScript/reuseCore2.js"></script>
		<script src="resources/JavaScript/formulaScreen.js"></script>
    	<script>
    	var imgLinkSource = "resources/images/btnLink.gif";
    	var imgRemoveSource = "resources/images/btnRemove.png";
    	var imgUpSource = "resources/images/btnUp.png";
    	var imgDownSource = "resources/images/btnDown.png";
    	var imgAddSource = "resources/images/btnAdd.png";
    	var imgFormulaSource = "resources/images/btnFormula.png";
    	    	
    	//------------------- JS Event functions  ---------------------- //

    	function updateOtherOcurrences_JSEvent(oParameter){ updateOtherOcurrences(arguments[0].srcElement); }
    	function updateResult_JSEvent(oParameter){ updateResult(arguments[0].srcElement); }
    	function crtNameChanged_JSEvent(oParameter){ crtNameChanged(arguments[0].srcElement); }
    	function reuseCriterion_JSEvent(oParameter){ reuseCriterion(arguments[0].srcElement); }
    	function reuseCase_JSEvent(oParameter){ reuseCase(arguments[0].srcElement); }
    	function reuseValue_JSEvent(oParameter){ reuseValue(arguments[0].srcElement); }
    	function addCriterion_JSEvent(oParameter){ addCriterion(arguments[0].srcElement); }
    	function removeCriterion_JSEvent(oParameter){ removeCriterion(arguments[0].srcElement); }
    	function addCase_JSEvent(oParameter){ before_addMetCase(arguments[0].srcElement); }
    	function showValueOrigin_JSEvent(oParameter){ showOrigin('value', arguments[0].srcElement); }
    	function showCriterionOrigin_JSEvent(oParameter){ showOrigin('criterion', arguments[0].srcElement); }
    	function showFormula_JSEvent(oParameter){ showFormula(arguments[0].srcElement);}
    	function moveCriterionUp_JSEvent(oParameter){moveParameter(true, arguments[0].srcElement);}
    	function moveCriterionDown_JSEvent(oParameter){moveParameter(false, arguments[0].srcElement);}

    	//------------------------------------------------------------- //

    	function before_addMethod()
    	{
    		var cases =  [{"name": "", "ID": generateID()}, {"name": "", "ID": generateID()}];
    		var reqCases = getXmlHttpRequestObject();
    		
    		function handleRequest()  
    		{  
    		    if (reqCases.readyState == 4 && reqCases.status == 200) 
    		    {
    		     	eval("var response = ("+reqCases.responseText+")");
    		     	if(response != "ERROR" && response.length > 0)
    		     		cases = response;
    		    }
    		}
    			
    		sendRequest(reqCases, "method", "loadRelatedCases", handleRequest);
    		
    		var mainCrt = {"ID": generateID(), "name": "", "description": "", "cases": cases};
    		var mainMet = {"ID": generateID(), "name": "", "parameters": [{"name": "", "ID": generateID()}, {"name": "", "ID": generateID()}, {"name": "", "ID": generateID()}]};
    		
    		addMethod(mainCrt, mainMet);
    	}

    	function addMethod(mainCrt, mainMet)
    	{
    		var cachedForm =  document.getElementById("frMethod").innerHTML; //Save the form state, so if a problem happen we can undo the changes
    		
    		try
    		{
    			mainMet.ID = generateID();
    			var colCount = mainCrt.cases.length *3 + 1;
    			var tab = document.createElement("table");
    			tab.setAttribute("id", mainCrt.ID);
    			tab.setAttribute("class", "table");
    			tab.setAttribute("title", mainCrt.name);
    			tab.setAttribute("summary", "methodProperties");
    			
    			var tabHead = document.createElement("thead");
    				
    			//Creating first table line...
    			var row = tabHead.insertRow(0);
    			var rowCell1 = row.insertCell(0);
    			rowCell1.setAttribute("class","tableHeader");
    			rowCell1.setAttribute("colspan", colCount); 
    			rowCell1.setAttribute("id","nameHeader" + mainCrt.ID);
    			var mainCrtName = createInputField("name" + mainCrt.ID, "", "text", mainCrt.name, "tableCaption", "onchange", crtNameChanged_JSEvent);
    			var btnMainCrtReuse = createImageButton("link" + mainCrt.ID, imgLinkSource, reuseValue_JSEvent, "smallImgButton");
    			rowCell1.appendChild(mainCrtName);
    			rowCell1.appendChild(btnMainCrtReuse);
    			
    			//Creating second table line...
    			var row2 = tabHead.insertRow(1);
    			var row2Cell1 = row2.insertCell(0);
    			row2Cell1.setAttribute("colspan", colCount); 
    			row2Cell1.setAttribute("id","descriptionHeader" + mainCrt.ID);
    			var description = document.createElement("textarea");
    			description.setAttribute("id","description" + mainCrt.ID);
    			description.setAttribute("class", "criterionDescription");
    			description.innerHTML = mainCrt.description;
    			row2Cell1.appendChild(description);
    			
    			//Creating third table line...
    			var row3 = tabHead.insertRow(2);
    			var row3Cell1 = row3.insertCell(0);
    			row3Cell1.setAttribute("class","parameterHeader");
    			row3Cell1.innerHTML = "Criteria - Parameter";
    			
    			for(var i = 0 ; i < mainCrt.cases.length ; i++)
    			{
    				var mainMetAppIdentifer = createInputField(generateID(), "methodApplications" + mainCrt.ID + mainCrt.cases[i].ID, "hidden");
    				row3.appendChild(mainMetAppIdentifer);
    				var caseIdentifier = createInputField(mainCrt.cases[i].ID, "caso" + mainCrt.ID, "hidden");
    				row3.appendChild(caseIdentifier);
    				
    				var row3cell2 = row3.insertCell(row3.cells.length);
    				var newCaseName = createInputField("name" + caseIdentifier.id, "", "text", mainCrt.cases[i].name); 
    				var btnCaseReuse = createImageButton("link" + mainCrt.cases[i].ID, imgLinkSource, reuseCase_JSEvent, "smallImgButton");
    				row3cell2.setAttribute("class", "tableHeader");
    				row3cell2.appendChild(newCaseName);
    				row3cell2.appendChild(btnCaseReuse);
    			}
    			
    			var row3Cell3 = row3.insertCell(row3.cells.length);
    			var addCase = createInputField(mainCrt.ID, "", "button", "Add Case", "buttonStyle", "onclick", addCase_JSEvent);
    			row3Cell3.appendChild(addCase);
    			tab.appendChild(tabHead);
    			
    			var tabBody = document.createElement("tbody");
    			var mainMethodIdentifier = createInputField("method" + mainCrt.ID, "", "hidden", mainMet.ID);
    			tabBody.appendChild(mainMethodIdentifier);
    			
    			//Creating parameters rows...
    			for(var i = 0 ; i < 3 ; i++)
    			{
    				var paramID = generateID();
    				var paramIdentifier = createInputField(paramID, "params" + mainMet.ID, "hidden");
    				tabBody.appendChild(paramIdentifier);
    				var bodyRow = tabBody.insertRow(0);
    				bodyRow.setAttribute("id", "param" + paramID);
    				var cell1 = document.createElement("td");
    				var paramName = createInputField("name" + paramID, "name" + paramID, "text", mainMet.parameters[i].name, "largeTextBox");
    				var btnParamReuse = createImageButton("link" + paramID, imgLinkSource, reuseCriterion_JSEvent, "smallImgButton");
    				cell1.appendChild(paramName);
    				cell1.appendChild(btnParamReuse);
    				bodyRow.appendChild(cell1);
    				
    				for(var j = 0 ; j < mainCrt.cases.length ; j++)
    				{
    					var metAppIdentifier = createInputField(generateID(), "methodApplications" + paramID + mainCrt.cases[j].ID, "hidden");
    					var paramMetIdentifier = createInputField(generateID(), "methods" + paramID, "hidden", mainCrt.cases[j].ID);
    					var valueIdentifier = createInputField("value" + paramMetIdentifier.id + mainCrt.cases[j].ID, "", "hidden", generateID());
    					tabBody.appendChild(metAppIdentifier);
    					tabBody.appendChild(paramMetIdentifier);
    					tabBody.appendChild(valueIdentifier);
    					
    					var cell2 = document.createElement("td");
    					var valueResult = createInputField("result" + valueIdentifier.value, "result" + valueIdentifier.value, "text", "", "mediumTextBox");
    					var valueUnit = createInputField("unit" + valueIdentifier.value, "unit" + valueIdentifier.value, "text", "", "smallTextBox");
    					var btnValueReuse = createImageButton("link" + paramID, imgLinkSource, reuseValue_JSEvent, "smallImgButton");
    					cell2.appendChild(valueResult);
    					cell2.appendChild(valueUnit);
    					cell2.appendChild(btnValueReuse);
    					bodyRow.appendChild(cell2);
    				}
    				
    				var cell3 = document.createElement("td");
    				var btnUp = createImageButton("img" + paramID, imgUpSource, moveCriterionUp_JSEvent, "smallImgButton");
    				var btnDown = createImageButton("img" + paramID, imgDownSource, moveCriterionDown_JSEvent, "smallImgButton");
    				var btnRemove = createImageButton("img" + paramID, imgRemoveSource, removeCriterion_JSEvent, "smallImgButton");
    				cell3.appendChild(btnUp);
    				cell3.appendChild(btnDown);
    				cell3.appendChild(btnRemove);
    				bodyRow.appendChild(cell3);
    			}
    			
    			var rowAddParameter = tabBody.insertRow(tabBody.rows.length);
    			var addParameter = createImageButton(mainCrt.ID, imgAddSource, addCriterion_JSEvent, "smallImgButton");
    			addParameter.name = "addParameter";
    			rowAddParameter.appendChild(addParameter);
    			
    			//Creating seventh table row...
    			var row7 = tabBody.insertRow(tabBody.rows.length);
    			var row7Cell1 = row7.insertCell(0);
    			row7Cell1.setAttribute("class","measureHeader");
    			row7Cell1.setAttribute("colspan", colCount); 
    			row7Cell1.setAttribute("id","derivedMeasures" + mainCrt.ID);
    			row7Cell1.innerHTML = "Criteria - Derived";
    			
    			//Creating eighth table row...
    			var row8 = tabBody.insertRow(tabBody.rows.length);
    			var row8Cell1 = row8.insertCell(0);
    			var rbMethodOutput = createInputField(mainMet.ID, mainMet.ID, "radio", mainCrt.ID);
    			rbMethodOutput.setAttribute("checked", "checked");
    			var methodOutputName = createInputField("methodOutput" + mainMet.ID, "", "text", "", "largeTextBox");
    			row8Cell1.appendChild(rbMethodOutput);
    			row8Cell1.appendChild(methodOutputName);
    			
    			for(var i = 0 ; i < mainCrt.cases.length ; i++)
    			{
    				var value = {"ID": generateID(), "stringResult": "", "unit":"", "source": ""};
    				
    				var resultIdentifier = createInputField(mainCrt.cases[i].ID + mainCrt.ID, "", "hidden", value.ID);
    				row8.appendChild(resultIdentifier);
    				
    				var row8Cell2 = row8.insertCell(row8.cells.length);
    				var resultLabel = document.createElement("label");
    				resultLabel.innerHTML = "NONE";
    				resultLabel.setAttribute("class", "resultLabel");
    				resultLabel.setAttribute("id", "result" + value.ID);
    				resultLabel.setAttribute("title", "Source: " + value.source);
    				resultLabel.onClick = showFormula_JSEvent;
    				resultLabel.attachEvent("onclick", showFormula_JSEvent);
    				var resultUnit = createInputField("unit" + value.ID, "unit" + value.ID, "text", "???", "smallTextBox", "onchange", updateOtherOcurrences_JSEvent);	
    				var resultReuse = createImageButton("formula" + value.ID, imgFormulaSource, showFormula_JSEvent, "smallImgButton");
    				row8Cell2.appendChild(resultLabel);
    				row8Cell2.appendChild(resultUnit);
    				row8Cell2.appendChild(resultReuse);
    			}
    			
    			//Creating last table row...
    			var lastRow = tabBody.insertRow(tabBody.rows.length);
    			var lastRowCell = lastRow.insertCell(0);
    			var addDerMeasure = createImageButton(mainCrt.ID, imgAddSource, addCriterion_JSEvent, "smallImgButton");
    			addDerMeasure.name = "addDerivedMeasure";
    			lastRowCell.appendChild(addDerMeasure);
    			
    			tab.appendChild(tabBody);
    			document.getElementById("frMethod").appendChild(tab);
    		}
    		catch(ex)
    		{
    			showErrorMessage("There was a problem while trying to insert a new method to the Business Case and the action couldn't be completed.", "Javascript Error");
    			document.getElementById("frMethod").innerHTML = cachedForm;
    		}
    	}

    	function before_addMetCase(srcElement)
    	{
    		var metID = document.getElementById("method" + srcElement.id).value;
    		addMetCase(srcElement, {"name": "", "ID": generateID(), "values": []}, metID);
    	}

    	function addMetCase(srcElement, caso, metID)
    	{
    		var table = findParentByTagName(srcElement, "TABLE");
    		//IE BUG: We have to use the innerHTML from the form because the IE has a bug that doesn't allow to change the table.innerHTML
    		var cachedForm =  document.getElementById("frMethod").innerHTML; //Save the form state, so if a problem happen we can undo the changes
    		
    		try
    		{
    			var caseIdentifier = createInputField(caso.ID, "caso" + table.id, "hidden");
    			table.appendChild(caseIdentifier);
    			
    			//Inserting new Cells in row 3
    			var row3 = table.rows[2];
    			var row3cell1 = row3.insertCell(row3.cells.length-1);
    			row3cell1.setAttribute("class", "tableHeader"); 
    			var newCaseName = createInputField("name" + caseIdentifier.id, "", "text", caso.name);
    			var btnCaseReuse = createImageButton("link" + caso.ID, imgLinkSource, reuseValue_JSEvent, "smallImgButton");
    			row3cell1.appendChild(btnCaseReuse);
    			row3cell1.appendChild(newCaseName);
    			
    			var metParameters = document.getElementsByName("params" + metID);
    			for(var i = 0 ; i < metParameters.length ; i++)
    			{
    				var metID = generateID();
    				var value = null;
    				
    				var caseValue = caso.values[metParameters[i].id];
    				if(caseValue == null)
    					value = {"ID": generateID(), "stringResult": "", "unit": ""};
    				else
    				{
    					metID = caseValue.methodID;
    					value = caseValue.value;
    				}
    				
    				var paramRow = table.rows[i+3];
    				var newParamRowCell = paramRow.insertCell(paramRow.cells.length-1);
    				
    				var metIdentifier = createInputField(metID, "", "hidden", "methods" + metParameters[i].id);
    				table.appendChild(metIdentifier);
    				
    				var valueIdentifier = createInputField("value" + metID,"", "hidden", value.ID);
    				newParamRowCell.appendChild(valueIdentifier);
    				
    				var vResult = createInputField("result" + value.ID, "result" + value.ID, "text", value.stringResult, "mediumTextBox", "onchange", updateResult_JSEvent);
    				newParamRowCell.appendChild(vResult);
    				
    				var vUnit = createInputField("unit" + value.ID, "unit" + value.ID, "text", value.unit, "smallTextBox", "onchange", updateResult_JSEvent);
    				newParamRowCell.appendChild(vUnit);
    				
    				var btnValueReuse = createImageButton("link" + caso.ID, imgLinkSource, reuseValue_JSEvent, "smallImgButton");
    				newParamRowCell.appendChild(btnValueReuse);
    			}
    			
    			document.getElementById("nameHeader" + table.id).setAttribute("colspan", row3.cells.length);;
    			document.getElementById("descriptionHeader" + table.id).setAttribute("colspan", row3.cells.length);;
    			document.getElementById("derivedMeasures" + table.id).setAttribute("colspan", row3.cells.length);;
    		}
    		catch(ex)
    		{
    			showErrorMessage("There was a problem while trying to insert a new parameter (criterion) to the method and the action couldn't be completed.", "Javascript Error");
    			document.getElementById("frMethod").innerHTML = cachedForm;
    		}
    	}

    	function addCriterion(srcElement)
    	{
    		var addFunction = srcElement.name;
    		var metID = document.getElementById("method" + srcElement.id).value;
    		if(addFunction == "addParameter")
    			addParameter(srcElement, {"name": "", "ID": generateID(), "values": []}, metID);
    		else
    			addDerivedMeasure(srcElement, metID);
    	}

    	function addDerivedMeasure(srcElement, metID)
    	{
    		var table = findParentByTagName(srcElement, "TABLE");
    		
    		//IE BUG: We have to use the innerHTML from the form because the IE has a bug that doesn't allow to change the table.innerHTML
    		var cachedForm =  document.getElementById("frMethod").innerHTML; //Save the form state, so if a problem happen we can undo the changes
    		
    		try
    		{
    			var currentRow = findParentByTagName(srcElement, "TR");
    			var newRow = table.insertRow(table.rows.length-3);
    			
    			var derMeasureID = generateID();
    			var newRowCell1 = newRow.insertCell(0);
    			var rbDerMeasure = createInputField(metID, metID, "radio", derMeasureID);
    			var measureName = createInputField("","measures" + metID, "text", "", "largeTextBox");
    			newRowCell1.appendChild(rbDerMeasure);
    			newRowCell1.appendChild(measureName);
    			
    			var cases = document.getElementsByName("caso" + table.id); 
    			for(var i = 0 ; i < cases.length ; i++)
    			{
    				var valueID = generateID();
    				var derMeasureValueIdentifier = createInputField(cases[i].ID + derMeasureID, "", "hidden", valueID);
    				newRow.appendChild(derMeasureValueIdentifier);
    				
    				var column2 = newRow.insertCell(1);
    				var vResult = document.createElement("label");
    				vResult.id = "result + valueID";
    				vResult["onclick"] = showFormula_JSEvent;
    				vResult.innerHTML = "NONE";
    				vResult.setAttribute("class","resultLabel");
    				var vUnit = createInputField("unit" + valueID, "unit" + valueID, "text", "???", "smallTextBox", "onchange", updateOtherOcurrences_JSEvent);
    				var btnReuse = createImageButton("formula" + valueID, imgFormulaSource, showFormula_JSEvent, "smallImgButton");
    				column2.appendChild(vResult);
    				column2.appendChild(vUnit);
    				column2.appendChild(btnReuse);
    			}
    			
    			currentRow.parentNode.insertBefore(newRow, currentRow);
    		}
    		catch(ex)
    		{
    			showErrorMessage("There was a problem while trying to insert a new parameter (criterion) to the method and the action couldn't be completed.", "Javascript Error");
    			document.getElementById("frMethod").innerHTML = cachedForm;
    		}
    	}

    	function addParameter(srcElement, criterion, metID)
    	{
    		var table = findParentByTagName(srcElement, "TABLE");
    		
    		//IE BUG: We have to use the innerHTML from the form because the IE has a bug that doesn't allow to change the table.innerHTML
    		var cachedForm =  document.getElementById("frMethod").innerHTML; //Save the form state, so if a problem happen we can undo the changes
    		
    		try
    		{
    			var currentRow = findParentByTagName(srcElement, "TR");
    			var newRow = table.insertRow(table.rows.length-3);
    			
    			var paramIdentifier = createInputField(criterion.ID, "params" + metID, "hidden");
    			table.appendChild(paramIdentifier);
    			
    			newRow.setAttribute("id", "param" + paramIdentifier.id);
    			
    			var column1 = newRow.insertCell(0);
    			var tbxCrtName = createInputField("name" + paramIdentifier.id, "name" + paramIdentifier.id, "text", criterion.name, "largeTextBox");
    			var btnCrtReuse = createImageButton("link" + paramIdentifier.id, imgLinkSource, reuseCriterion_JSEvent, "smallImgButton");
    			column1.appendChild(tbxCrtName);
    			column1.appendChild(btnCrtReuse);
    			
    			var cases = document.getElementsByName("caso" + table.id); 
    			for(var i = 0 ; i < cases.length ; i++)
    			{
    				var crtValue = {"value": {"ID": generateID(), "stringResult": "", "unit": "", "source": ""}, "methodID": generateID(), "metAppID": generateID()};
    				
    				var metAppIdentifier = createInputField(crtValue.metAppID, "methodApplications" + paramIdentifier.id + cases[i].id, "hidden");
    				newRow.appendChild(metAppIdentifier);
    				
    				var metIdentifier = createInputField(crtValue.metID, "methods" + paramIdentifier.id , "hidden", cases[i].id);
    				newRow.appendChild(metIdentifier);
    				
    				var valueIdentifier = createInputField("value" + crtValue.metID + cases[i].id, "", "hidden", crtValue.value.ID);
    				newRow.appendChild(valueIdentifier);
    				
    				var column2 = newRow.insertCell(1);
    				var vResult = createInputField("result" + crtValue.value.ID, "result" + crtValue.value.ID, "text", crtValue.value.stringResult, "mediumTextBox", "onchange", updateResult_JSEvent);
    				var vUnit = createInputField("unit" + crtValue.value.ID, "unit" + crtValue.value.ID, "text", crtValue.value.unit, "smallTextBox", "onchange", updateOtherOcurrences_JSEvent);
    				var btnReuse = createImageButton("link" + paramIdentifier.id, imgLinkSource, reuseCriterion_JSEvent, "smallImgButton");
    				column2.appendChild(vResult);
    				column2.appendChild(vUnit);
    				column2.appendChild(btnReuse);
    			}
    			
    			var column3 = document.createElement("td");
    			var btnUp = createImageButton("img" + metID, imgUpSource, moveCriterionUp_JSEvent, "smallImgButton");
    			var btnDown = createImageButton("img" + metID, imgDownSource, moveCriterionDown_JSEvent, "smallImgButton");
    			var btnRemove = createImageButton("img" + metID, imgRemoveSource, removeCriterion_JSEvent, "smallImgButton");
    			column3.appendChild(btnUp);
    			column3.appendChild(btnDown);
    			column3.appendChild(btnRemove);
    			newRow.appendChild(column3);
    			
    			currentRow.parentNode.insertBefore(newRow, currentRow);
    		}
    		catch(ex)
    		{
    			showErrorMessage("There was a problem while trying to insert a new parameter (criterion) to the method and the action couldn't be completed.", "Javascript Error");
    			document.getElementById("frMethod").innerHTML = cachedForm;
    		}
    	}

    	function encapsulateAllJSONData()
    	{
    		var jsonData = [];
    		var methods = [];
    			
    		var allTables = document.getElementsByTagName("table");
    			
    		for (var i=0; i < allTables.length; i++) //Necessary loop to take only the tables that represent methods and not the SAPUI5 tables.
    			if(allTables[i].summary == "methodProperties")
    				methods.push(allTables[i]); //Add only the methods tables
    			
    		for(var i=0; i < methods.length; i++)
    		{
    			var jsonMethodApplications = encapsulateJSONData(methods[i]);
    			jsonData.push(jsonMethodApplications);
    		}
    			
    		return jsonData;
    	}

    	function encapsulateJSONData(table)
    	{
    		var methodApplications = [];
    		var jsonMethodApplications = {"mainMethod": {}, "cases": [], "methodApplications": methodApplications, "derMeasure": null};
    		
    		var crtID = table.id;
    		var mainCrtName = document.getElementById("name" + crtID).value;
    		var mainDescription = document.getElementById("description" + crtID).value;
    		jsonCriterion = {"ID": crtID, "name": mainCrtName, "description": mainDescription}; 
    		var mainMetID = getChildElementByProperty(table, "id", "method" + crtID).value;
    		var jsonMainMethod = {"ID": mainMetID, "name": getChildElementByProperty(table, "id", "methodOutput" + mainMetID).value, "parameters": []}; 
    		var jsonCases = [];
    		
    		var radioButtons = getChildElementsByProperty(table, "name", mainMetID);
    		for(var j = 0 ; j < radioButtons.length ; j++)
    		{
    			var currentMeasure = radioButtons[j];
    			if(currentMeasure.checked && currentMeasure.defaultValue != crtID)
    				jsonMethodApplications.derMeasure = {"ID": currentMeasure.value, "name": getChildElementByProperty(table, "name", "measures" + jsonMainMethod.ID).value}; 
    		}
    		
    		var criterionCases = getChildElementsByProperty(table, "name", "caso" + crtID);
    		for(var j = 0 ; j < criterionCases.length ; j++)
    		{
    			var caseID = criterionCases[j].id;
    			var caseName = document.getElementById("name" + caseID).value;
    			var jsonCase = {"ID": caseID, "name": caseName}; 
    			jsonCases.push(jsonCase);
    			
    			var valID = getChildElementByProperty(table, "id", caseID + crtID).value; 
    			var valResult = getChildElementByProperty(table, "id", "result" + valID).innerHTML; 
    			var valUnit = getChildElementByProperty(table, "id", "unit" + valID).value; 
    			var jsonValue = {"ID": valID, "stringResult": valResult, "unit": valUnit};
    		
    			var jsonMethodApplication = {"criterion": {}, "method": {}, "caso": {}, "value": {}, "ID":""};
    			
    			jsonMethodApplication.criterion = jsonCriterion;
    			jsonMethodApplication.method = jsonMainMethod;
    			jsonMethodApplication["caso"] = jsonCase;
    			jsonMethodApplication.value = jsonValue;
    			jsonMethodApplication.ID = getChildElementByProperty(table, "name", "methodApplications" + jsonCriterion.ID + caseID).id;  
    			
    			methodApplications.push(jsonMethodApplication);
    		}
    		
    		jsonMethodApplications.cases = jsonCases;
    		
    		var metParameters = getChildElementsByProperty(table, "name", "params" + jsonMainMethod.ID);
    		for(var k = 0 ; k < metParameters.length ; k++)
    		{
    			var paramID = metParameters[k].id;
    			var paramName = document.getElementById("name" + paramID).value;
    			var jsonParam = {"ID": paramID, "name": paramName};
    			
    			var methods = getChildElementsByProperty(table, "name", "methods" + paramID); 
    			for(var l = 0 ; l < methods.length ; l++)
    			{
    				var metID = methods[l].id;
    				var caseID = methods[l].value;
    				
    				var valueID = getChildElementByProperty(table, "id", "value" + metID + caseID).value; 
    				vResult = getChildElementByProperty(table, "id", "result" + valueID).value; 
    				if(vResult == null)
    					vResult = getChildElementByProperty(table, "id", "result" + valueID).innerHTML; 
    				vUnit = getChildElementByProperty(table, "id", "unit" + valueID).value;
    				
    				var jsonValue = {"ID": valueID, "stringResult": vResult, "unit": vUnit};
    				var jsonMethod = {"ID": metID, "value": jsonValue};
    				
    				var jsonMethodApplication = {"criterion": {}, "method": {}, "caso": {}, "value": {}, "ID": "", "parentMetID": ""};
    				
    				jsonMethodApplication.criterion = jsonParam;
    				jsonMethodApplication.method = jsonMethod;
    				jsonMethodApplication["caso"] = jsonCases.searchElement("ID", caseID);
    				jsonMethodApplication.value = jsonValue;
    				jsonMethodApplication.parentMetID = mainMetID;
    				jsonMethodApplication.ID = getChildElementByProperty(table, "name", "methodApplications" + jsonParam.ID + caseID).id;
    				
    				methodApplications.push(jsonMethodApplication);
    			}
    			
    			jsonMainMethod.parameters.push(jsonParam);
    			jsonMethodApplications.mainMethod = jsonMainMethod;
    		}
    		
    		return jsonMethodApplications;
    	}

    	function verifyPendingChanges()
    	{
    		return false;
    	}

    	function validateForm()
    	{
    		function prepareParameter(jsonData)
    		{
    			var param = "&methodApplications=" + transformJSON(jsonData.methodApplications);
    			param += "&cases=" + transformJSON(jsonData.cases);
    			param += "&mainMethod=" + transformJSON(jsonData.mainMethod);
    			
    			return param;
    		}
    		
    		var isValid = false;
    		var validateReq = getXmlHttpRequestObject();
    		var jsonData = encapsulateAllJSONData();
    		var i = 0;
    		
    		function handleError()
    	    {
    	    	if (validateReq.readyState == 4 && validateReq.status == 200) 
    	    	{
    	    		eval("var response = ("+validateReq.responseText+")");
    	    		showSpecifcErrorMessage(response);
    	    	}
    	    }
    		
    		function handleRequest()  
    		{  
    			if (validateReq.readyState == 4 && validateReq.status == 200) 
    		    {
    		     	eval("var response = ("+validateReq.responseText+")");
    		     	
    		     	if(response == "")
    		     		isValid = true;
    		     	else //Treat the possible errors types and show an adequate message...
    		     	{
    		     		i = jsonData.length;
    		     		if(!showSpecifcErrorMessage(response))
    			     		showValidationError(response);
    		     	}
    		    }
    		}
    		
    		for(i = 0 ; i < jsonData.length ; i++)
    	 		sendRequest(validateReq, "method", "validateChanges", handleRequest, prepareParameter(jsonData[i]));
    		
    		if(isValid)
    		{
    			validateReq = getXmlHttpRequestObject();
    			sendRequest(validateReq, "method", "saveMethodData", handleError, "&saveData=" + transformJSON(jsonData));
    		}
    		
    		return isValid;
    	}

    	function updateOtherOcurrences(sourceElement)
    	{
    		//Update input fields...
    		var elements = document.getElementsByName(sourceElement.name);
    		for(var i = 0 ; i < elements.length ; i++)
    			elements[i].value = sourceElement.value;
    		
    		//Update hyperlinks...
    		var hyperLinks = document.getElementsByTagName("A");
    		for(var i = 0 ; i < hyperLinks.length ; i++)
    			if(hyperLinks[i].id == sourceElement.id)
    				hyperLinks[i].innerHTML = sourceElement.value;
    	}

    	function updateResult(oParameter)
    	{
    		updateOtherOcurrences(oParameter);
    		var updateReq = getXmlHttpRequestObject();
    		
    		function handleRequest()  
    		{  
    			if (updateReq.readyState == 4 && updateReq.status == 200 && updateReq.responseText != "") 
    		    {
    		     	eval("var response = ("+updateReq.responseText+")");
    		     	
    		     	if(typeof response != "string")
    		     		refreshResultFields(response);
    		     	else //Treat the possible errors types and show an adequate message...
    		     	{
    		     		i = jsonData.length;
    		     		showSpecifcErrorMessage(response);
    		     	}
    		    }
    		}
    		
    		var param = "&valID=" + transformJSON(oParameter.name.replace("result",""));  
    		param += "&stringResult=" + encodeURIComponent(oParameter.value);
    		sendRequest(updateReq, "method", "updateResult", handleRequest, param);
    	}

    	function removeCriterion(srcElement)
    	{
    		try
    		{
    			function callback(oAction)
    			{
    				if(oAction == sap.ui.commons.MessageBox.Action.YES)
    				{
    					var reqRemove = getXmlHttpRequestObject();
    					var table = findParentByTagName(srcElement, "TABLE");
    					var mainCrtID = table.id;
    					var crtID = srcElement.id.replace("img","");
    					var calMetID = getChildElementByProperty(table, "id", "method" + mainCrtID).value;
    					var methodApplications = [];
    					
    					function handleRequest()  
    					{  
    						if (reqRemove.readyState == 4 && reqRemove.status == 200) 
    					    {
    							eval("var response = (" + reqRemove.responseText + ")");
    							if(response == "")
    							{
    								var currentRow = findParentByTagName(srcElement, "TR");
    								currentRow.parentNode.removeChild(currentRow);
    								
    								var paramIdentifier = getChildElementByProperty(table, "id", crtID);
    								paramIdentifier.parentNode.removeChild(paramIdentifier);
    							}
    							else
    								showSpecifcErrorMessage(response);
    					    }
    					}
    					
    					var criterionCases = document.getElementsByName("caso" + mainCrtID);
    					var crtMethods = document.getElementsByName("methods" + crtID);
    					for(var j = 0 ; j < criterionCases.length ; j++)
    					{
    						var casID = criterionCases[j].id;
    						var metAppID = getChildElementByProperty(table, "name", "methodApplications" + crtID + casID).id;
    						var metID = crtMethods[j].id;
    						var valID = document.getElementById("value" + metID + casID).value;
    						var jsonMethodApplication = {"criterion": {"ID": crtID}, "method": {"ID": metID}, "caso": {"ID": casID}, "value": {"ID": valID}, "ID": metAppID};
    						methodApplications.push(jsonMethodApplication);
    					}
    					
    					var param = "&crtID=" + transformJSON(crtID);  
    					param += "&calMetID=" + transformJSON(calMetID);
    					param += "&metApps=" + transformJSON(methodApplications);
    					
    					sendRequest(reqRemove, "method", "removeParameter", handleRequest, param);
    				}
    			}
    			
    			sap.ui.commons.MessageBox.show("Are you sure you want to remove this parameter and all of its related data?", sap.ui.commons.MessageBox.Icon.QUESTION, "Remove Confirmation", [sap.ui.commons.MessageBox.Action.YES, sap.ui.commons.MessageBox.Action.NO], callback);
    		}
    		catch(ex)
    		{ 
    			showErrorMessage("There was a problem while trying to remove the parameter from the method and the action couldn't be completed.", "Javascript Error"); 
    		}
    	}

    	function moveCriterionUp(srcElement)
    	{
    		moveParameter(true, srcElement);
    	}

    	function moveCriterionDown(srcElement)
    	{
    		moveParameter(false, srcElement);
    	}

    	function moveParameter(moveUp, srcElement)
    	{
    		var currentRow = findParentByTagName(srcElement, "TR");
    		var table = findParentByTagName(currentRow, "TABLE");
    		var currentIndex = currentRow.rowIndex; 
    		if(moveUp)
    		{
    			var otherRow = table.rows[currentIndex - 1];
    			if(otherRow.id.indexOf("param") != -1)
    				otherRow.parentNode.insertBefore(currentRow,otherRow);
    		}
    		else
    		{
    			var otherRow = table.rows[currentIndex + 1]; 
    			if(otherRow.id.indexOf("param") != -1)
    				currentRow.parentNode.insertBefore(otherRow,currentRow);
    		}
    	}

    	function showOrigin(cmpType, srcElement)
    	{
    		var componentReq = getXmlHttpRequestObject();
    		
    		function handleRequest()  
    		{  
    			if (componentReq.readyState == 4 && componentReq.status == 200) 
    		    {
    		     	eval("var response = ("+componentReq.responseText+")");
    		     	
    		     	if(typeof response != "string")
    		     	{
    		     		var cmpName = (cmpType == "value") ? response.value.stringResult : response.criterion.name;
    		     		var message = "The cmpType 'crtName' is reused from the method 'metName' in Business Case 'XXX'.";
    		     		message = message.replace("cmpType", cmpType);
    		     		message = message.replace("crtName", cmpName);
    		     		message = message.replace("metName", response.method.name);
    		     		
    		     		showErrorMessage(message);
    		     	}
    		     	else
    		     		showSpecifcErrorMessage(response);
    		    }
    		}
    		var cmpID = srcElement.id.replace("link","");
    		var param = "&cmpID=" + encodeURIComponent(cmpID);
    		param += "&cmpType=" + encodeURIComponent(cmpType);
    		sendRequest(componentReq, "method", "getComponentByID", handleRequest, param);
    	}
    	</script>
	</head>
	<body onload="initializePage('lnkMethod','BCF - Methods Definition')">
		<%@include file="/webPages/_header.jsp" %>
     	<div id="preview" class="sapUiBody" >
			<form id="frMethod" title="Method Form" action="method" method="post">
 				<input type="button" id="btnAddMethod" class="buttonStyle" value="Add more methods..." onclick="before_addMethod()">
					<c:forEach var="mainCrt" items="${Criteria}"> <%-- Each of the top level criterion/method is represented as a table --%>
						<c:set var="cases" value="${SessionDAO.getCriterionRelatedCases(mainCrt.ID)}" />
						<c:set var="method" value="${SessionDAO.getCriterionRelatedCases(mainCrt.ID)}" />
						<c:set var="colSpan" value="${cases.size()*3 + 1}"/>
						<table summary="methodProperties" title="${mainCrt.name}" id="${mainCrt.ID}" class="table">
						<thead>
							<tr>  <%-- First row: Main criterion Name--%>
			                	<th class="tableHeader" colspan="${colSpan}" id="nameHeader${mainCrt.ID}">
			                		<input type="text" class="tableCaption" id="name${mainCrt.ID}" name="name${mainCrt.ID}" value="${mainCrt.name}" onchange="updateOtherOcurrences(this)">
			                		<img src="resources/images/btnLink.gif" id="link${mainCrt.ID}" onclick="reuseMethod(this)" class="smallImgButton">
			                	</th>
			                <tr> <%-- Second row: Main criterion Description (Span row)--%>
			                	<th colspan="${colSpan}" id="descriptionHeader${mainCrt.ID}" >
			                		<textarea id="description${mainCrt.ID}" class="criterionDescription">${mainCrt.description}</textarea>
			                	</th>
		                	</tr>
			                <tr> <%-- Third row: Main criterion Cases names data column--%>
		                  		<th class="parameterHeader">Criteria - Parameters</th> 
		                  		<c:forEach var="caso" items="${cases}"> <%-- Interate through the cases --%>
		                  			<input type="hidden" id="${SessionDAO.getMethodApplication(mainCrt,caso, null).ID}" name="methodApplications${mainCrt.ID}${caso.ID}">
		                  			<input type="hidden" id="${caso.ID}" name="caso${mainCrt.ID}">
		                  			<th class="tableHeader">
		                  				<input type="text" id="name${caso.ID}" value="${caso.name}" name="name${caso.ID}" onchange="updateOtherOcurrences(this)">
		                  				<img src="resources/images/btnLink.gif" id="link${caso.ID}" onclick="reuseCase(this)" class="smallImgButton">
		                  			</th>
		                  		</c:forEach>
		                  		<th><input id="${mainCrt.ID}" type="button" value="Add Case" onclick="before_addMetCase(this)"></th> 
		              		</tr>
		              		</thead>
		              		<tbody>
		              		<c:forEach var="method" items="${SessionDAO.getCriterionCalculationMethods(mainCrt.ID)}">
		              			<input type="hidden" value="${method.ID}" id="method${mainCrt.ID}">
		              			<c:forEach var="crt" items="${method.parameters}">
		              			<input type="hidden" name="params${method.ID}" id="${crt.ID}">
			              		<tr id="param${crt.ID}"> <%-- Forth row: Method parameters and their values --%>
				                    <td>
                    				<c:choose>
                    					<c:when test="${SessionDAO.isOrigin(SessionDAO.getMethodApplication(crt, method.ID), crt.ID, 'criterion')}">
											<c:if test="${!SessionDAO.isParameterUsed(method.ID, crt.ID)}">
												<img src="resources/images/btnWarning.png" class="smallImgButton">
											</c:if>
											<input id="name${crt.ID}" name="name${crt.ID}" value="${crt.name}" class="largeTextBox" onchange="updateOtherOcurrences(this)">
				                    		<img src="resources/images/btnLink.gif" id="link${crt.ID}" onclick="reuseCriterion(this)" class="smallImgButton">  
   										</c:when>
										<c:otherwise>
											<input id="name${crt.ID}" name="name${crt.ID}" value="${crt.name}" disabled="disabled" class="largeTextBox" onchange="updateOtherOcurrences(this)">
				                    		<img src="resources/images/btnLink.gif" id="link${crt.ID}" class="smallImgButton" onclick="showOrigin('criterion', this)">
										</c:otherwise>
									</c:choose>
				                    </td>
				                    <c:forEach var="caso" items="${cases}">
				                    	<c:set var="metApp" value="${SessionDAO.getMethodApplication(crt, caso, method.ID)}" />
			                    	 	<input type="hidden" id="${metApp.ID}" name="methodApplications${crt.ID}${caso.ID}">
			                    	 	<input type="hidden" name="methods${crt.ID}" value="${metApp.getCaso().getID()}" id="${metApp.getMethod().getID()}">
			                    	 	<input type="hidden" value="${metApp.getValue().getID()}" id="value${metApp.getMethod().getID()}${metApp.getCaso().getID()}">
			                    		<td id="case${metApp.getCaso().getID()}">
				                    		<c:choose>
                   							<c:when test="${SessionDAO.isOrigin(metApp, crt.ID, 'criterion')}">
                   								<input type="text" class="mediumTextBox" value="${metApp.getValue().stringResult}" id="result${metApp.getValue().ID}" name="result${metApp.getValue().ID}" title="Source: ${metApp.getValue().source}" onchange="updateResult(this)">
	                  							<input type="text" class="smallTextBox" id="unit${metApp.getValue().ID}" name="unit${metApp.getValue().ID}" value="${metApp.getValue().unit}" onchange="updateOtherOcurrences(this)">
	                  							<img src="resources/images/btnLink.gif" id="link${metApp.getValue().ID}" onclick="reuseValue(this)" class="smallImgButton">
  												</c:when>
											<c:otherwise>
												<input type="text" class="mediumTextBox" value="${metApp.getValue().stringResult}" id="result${metApp.getValue().ID}" name="result${metApp.getValue().ID}" title="Source: ${metApp.getValue().source}" disabled="disabled" onchange="updateResult(this)">
	                  							<input type="text" class="smallTextBox" id="unit${metApp.getValue().ID}" name="unit${metApp.getValue().ID}" value="${metApp.getValue().unit}" disabled="disabled" onchange="updateOtherOcurrences(this)">
	                  							<img src="resources/images/btnLink.gif" id="link${metApp.getValue().ID}" onclick="showOrigin('value', this)" class="smallImgButton">
											</c:otherwise>
											</c:choose>
                  						</td>
		                  			</c:forEach>
		                  			<td>
		                  				<img src="resources/images/btnUp.png" id="img${crt.ID}" onclick="moveCriterionUp(this)" class="smallImgButton">
		                  				<img src="resources/images/btnDown.png" id="img${crt.ID}" onclick="moveCriterionDown(this)" class="smallImgButton">
		                  				<img src="resources/images/btnRemove.png" id="img${crt.ID}" onclick="removeCriterion(this)" class="smallImgButton">
	                  				</td>
			               		 </tr>
		                		</c:forEach>
		                		 <tr>
			               		 	<td>
		                  				<img src="resources/images/btnAdd.png"  name="addParameter" id="${mainCrt.ID}" onclick="addCriterion(this)" class="smallImgButton">
                  					</td>
			               		 </tr>
		                		<tr> <%-- Fifth row: Derived measures header (Span row) --%>
		              				<th id="derivedMeasures${mainCrt.ID}" colspan="${colSpan}" class="measureHeader">Criteria - Derived</th>
	              				</tr>
		                		<c:forEach var="derMeasure" items="${method.derivedMeasures}">
		              				<tr> <%-- Last row: Criterion's main method application result data --%>
		              					<td>
				                    		<input type="radio" name="${method.ID}" value="${derMeasure.ID}" id="${method.ID}">
				                    		<input class="largeTextBox" name="measures${method.ID}" value="${derMeasure.name}">
			                    		</td>
			                    		<c:forEach var="caso" items="${cases}">
			                  		 		<c:set var="value" value="${SessionDAO.getRelatedValue(derMeasure.ID, caso.ID)}" /> <%-- TODO: Change this..if the criterion is reused then it cannot know which value take. use parentID --%>
			                  		 		<input type="hidden" value="${value.ID}" id="${caso.ID}${derMeasure.ID}">
			                  		 		<td>
												<c:if test="${value.hasError}">
			                  		 				<img src="resources/images/btnWarning.png" class="smallImgButton" title="There is some parameter missing. The missing value has been replaced by 1.">
				                    			</c:if>
												<label class="resultLabel" id="result${value.ID}" title="Source: ${value.source}" onclick="showFormula(this)">${value.stringResult}</label>
		                    					<input type="text" class="smallTextBox" id="unit${value.ID}" name="unit${value.ID}" value="${value.unit}" onchange="updateOtherOcurrences(this)">
		                    					<img src="resources/images/btnFormula.png" id="formula${value.ID}" onclick="showFormula(this)" class="smallImgButton">
			                    			</td>
		                  				</c:forEach>
		                  				<%-- <td><img src="resources/images/btnRemove.png" id="img${derMeasure.ID}" onclick="removeCriterion(this)" class="smallImgButton"> </td>--%>
			              			</tr>	
	                			</c:forEach>
	                				<tr> <%-- Last row: Criterion's main method application result data --%>
		              					<td>
				                    		<input type="radio" name="${method.ID}" value="${mainCrt.ID}" checked="checked">
				                    		<input class="largeTextBox" id="methodOutput${method.ID}" value="${method.name}">
			                    		</td>
			                    		<c:forEach var="caso" items="${cases}">
			                  		 		<c:set var="value" value="${SessionDAO.getRelatedValue(mainCrt.ID, caso.ID)}" /> <%-- TODO: Change this..if the criterion is reused then it cannot know which value take. use parentID --%>
			                  		 		<input type="hidden" value="${value.ID}" id="${caso.ID}${mainCrt.ID}">
			                  		 		<td id="finalResultColumn${caso.ID}">
												<c:if test="${value.hasError}">
			                  		 				<img src="resources/images/btnWarning.png" class="smallImgButton" title="There is some parameter missing. The missing value has been replaced by 1.">
				                    			</c:if>
												<label class="resultLabel" id="result${value.ID}" title="Source: ${value.source}" onclick="showFormula(this)">${value.stringResult}</label>
		                    					<input type="text" class="smallTextBox" id="unit${value.ID}" name="unit${value.ID}" value="${value.unit}" onchange="updateOtherOcurrences(this)">
		                    					<img src="resources/images/btnFormula.png" id="formula${value.ID}" onclick="showFormula(this)" class="smallImgButton">
			                    			</td>
		                  				</c:forEach>
			              			</tr>
	                			<tr>
			               		 	<td>
		                  				<img src="resources/images/btnAdd.png" name="addDerivedMeasure" id="${mainCrt.ID}" onclick="addCriterion(this)" class="smallImgButton">
                  					</td>
			               		 </tr>
		              		</c:forEach>
		              		</tbody>
	         			</table>
					</c:forEach> 
 			</form>
 			<input id="method" type="button" value="Save" class="buttonStyle" onclick="validateForm()">
      	</div>
       	<%@include file="/webPages/_footer.jsp"%> 
	</body>
</html>